package com.haskie.product.controller;

import com.haskie.api.entity.Product;
import com.haskie.api.entity.User;
import com.haskie.api.utils.RedisUtil;
import com.haskie.api.utils.RedissonUtil;
import com.haskie.product.configBean.ProductConfig;
import com.haskie.product.feign.IUserFeignService;
import com.haskie.product.service.IProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@Api(value = "产品controller",tags = {"产品操作接口"})
public class ProductController {

//    @Autowired
//    IUserFeignService userFeignService;
    @Autowired
    IProductService productService;
    @Autowired
    ProductConfig productConfig;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    RedissonUtil redissonUtil;

//    @GetMapping("/getAllUser/{id}")
//    @ApiOperation(value = "获取用户信息",tags = "获取用户信息",notes = "feign调用用户服务接口")
//    public User getAllUser(@PathVariable("id") String id){
//        User user = userFeignService.getAllUser(id);
//        return user;
//    }

    @GetMapping("/getProducts")
    @ApiOperation(value = "获取产品信息集合",tags = "获取产品信息集合",notes = "获取所有产品信息")
    public List<Product> getProducts(){
        return productService.getProducts();
    }

    @GetMapping("/getConfig")
    @ApiOperation(value = "获取产品配置信息", tags = {"获取产品信息Apollo"}, notes = "apollo配置的产品信息")
    public Object getConfig(){

        return productConfig;//config.getProperty("name","default");
    }

    @GetMapping("/getRedisDate")
    @ApiOperation(value = "获取redis值", tags = {"集成redis验证"}, notes = "集成redis验证")
    public String getRedisDate() {
        redisUtil.set("cjj_product", productConfig.getName());
        return (String) redisUtil.get("cjj_product");
    }

    @GetMapping(value = "/redisLock/{lockId}")
    @ApiOperation(value = "redisson分布式锁", tags = {"集成redisson验证"}, notes = "集成redisson验证")
    public void test(@PathVariable("lockId") String lockId) {

        RLock lock = redissonUtil.getRLock(lockId);
        try {
            boolean bs = lock.tryLock(5, 6, TimeUnit.SECONDS);
            if (bs) {
                // 业务代码
                log.info("进入业务代码: " + lockId);

                lock.unlock();
            } else {
                Thread.sleep(300);
            }
        } catch (Exception e) {
            log.error("", e);
            lock.unlock();
        }
    }
}
